var $ = require('node-jquery');
var fs = require('fs');
var templateFile = "weixin_template.htm";
var util = require('./util');
function parseWeixin (url,writeTo,preffix) {
    var defer = $.get(url,function(html) {
        var doc = $(html);
        var pageContent = doc.find('#page-content');
        pageContent.find('img').each(function () {
            var img = $(this);
            var url = img.attr('data-src');
            if(url){
                var base64 = util.base64EncodeFromUrl(url);
                img.attr('src',"data:image/png;base64,"+base64);
            }
        });
        var valueObj = {};
        valueObj['activity-name'] = doc.find('#activity-name').text();
        valueObj['post-user'] = doc.find('#post-user .text-ellipsis').text();
        valueObj['media'] = pageContent.find('#media').html();
        valueObj['title'] = doc.find('title').text();
        valueObj['content'] = pageContent.find('.text').html();
        valueObj['toolbar'] = pageContent.find('.page-toolbar').html('').append($('<a/>').text("阅读原文").attr('href',url).attr('target',"_blank")).html();

        var template = fs.readFileSync(templateFile,{encoding:'utf-8'});
        var reg = /{{(.*?)}}/g;
        var match;
        while((match=reg.exec(template))!==null){
            template = template.replace(match[0],valueObj[match[1]]);
            reg.lastIndex = 0;
        }
//		console.log(template);
        writeTo = writeTo||"";
        writeTo[writeTo.length-1]!="/" && (writeTo=writeTo+"/");
        if(!fs.existsSync(writeTo)){
            util.mkdirSync_p(writeTo,"0777");
        }
        var htmlFileName = valueObj['activity-name']+".html";
        if(preffix && htmlFileName.indexOf(preffix)<0){
            htmlFileName = preffix + htmlFileName;
        }
        var fileName = writeTo+htmlFileName;
        fs.writeFileSync(fileName,template);
        return fileName;
    });
    return defer;
}

module.exports={
    parseWeixin:parseWeixin
}